import simpleGit from 'simple-git';
import { consola as logger } from 'consola';
import { readFileSync, writeFileSync, appendFileSync } from 'fs';

const git = simpleGit();
const root = process.cwd();

const now = new Date()
const fixNum = (num: number, len: number = 2) => String(num).padStart(len, '0')
const lastModify = `${now.getFullYear()}-${fixNum(now.getMonth() + 1)}-${fixNum(now.getDate())} ${fixNum(now.getHours())}:${fixNum(now.getMinutes())}:${fixNum(now.getSeconds())}`

export default async (logPath?: string) => {
  await git.pull();
  const changedFile = await git.status()

  if (!changedFile.files.length) logger.error('没有修改文件，无需提交！')
  else {
    logger.info('git status：', changedFile.files.length);

    const changedLine = await git.diff(['--shortstat'])
    logger.info('git diff:', changedLine)

    const changedCounts = changedLine.replace(/[a-z|\(|\)|\+|\-|\s]/g, '').split(',').map(k => Number(k) || 0)
    logger.info('git changedCounts:', changedCounts)
    const updateFiles = changedCounts.slice(1)
    const addVersion = changedFile.files.length - changedCounts[0] + updateFiles.reduce((a, b) => a + b, 0)
    logger.info('git add version', addVersion)

    const tag = await logger.prompt('请选择', {
      type: 'select', options: [
        { value: '🐛 fix', label: '🐛 fix:          修复bug' },
        { value: '🎸 feat', label: '🎸 feat:         新功能' },
        { value: '🈴 merge', label: '🈴 merge:        分支合并' },
        { value: '💍 test', label: '💍 test:         正在添加缺少的测试' },
        { value: '🤖 chore', label: '🤖 chore:        构建过程或辅助工具更改' },
        { value: '✏️  docs', label: '✏️  docs:         仅文档更改' },
        { value: '💡 refactor', label: '💡 refactor:     一个既没有修复错误也没有添加功能的代码更改' },
        { value: '💄 style', label: '💄 style:        代码格式化' },
        { value: '🎡 ci', label: '🎡 ci:           CI/CD提交' },
        { value: '⚡️ perf', label: '⚡️ perf:         提高性能的代码更改' },
      ]
    });

    const info = JSON.parse(readFileSync(`${root}/package.json`, { encoding: 'utf-8' }))
    const ov = info.version
    const ovs = ov.split('.')
    const nv = `${ovs.slice(0, ovs.length - 1).join('.')}.${Number(ovs.at(-1)) + addVersion}`

    const v = await logger.prompt('请输入版本号', { type: 'text', initial: nv, placeholder: nv })
    let message = ''

    while (true) {
      message = await logger.prompt('请输入提交信息', { type: 'text', placeholder: '不超过55字' }) || ''

      if (message.length > 55) {
        logger.warn('提交信息过长，请重新输入')
        continue
      } else if (message.length < 3) {
        logger.warn('提交信息过短，请重新输入')
        continue
      } else {
        break
      }
    }

    message = `v${v}: ${tag} / ${message}`
    // 写入最新版本号
    writeFileSync(`${root}/package.json`, JSON.stringify({...info, version: v, lastModify}, null, 2))
    // 写入版本日志
    if (logPath) appendFileSync(`${root}${logPath}`, `${message}\n`, {flag: 'a+'})

    await git.add('.');
    await git.commit(message);
    await git.push();

    logger.info('提交成功！', message)
  }
}
